package com.waypolice.manager.controller;

import com.waypolice.base.BaseController;
import com.waypolice.common.utils.MathUtils;
import com.waypolice.manager.service.ActivitiService;
import com.waypolice.manager.service.UpmsUserRoleService;
import com.waypolice.manager.service.UserService;
import com.waypolice.pojo.UpmsRole;
import com.waypolice.pojo.UpmsUser;
import com.waypolice.pojo.UpmsUserRole;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.GroupQuery;
import org.activiti.engine.identity.User;
import org.activiti.engine.identity.UserQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 描述:
 *
 * @author zyp
 * @description 工作流用户与组控制层
 * @create 2019-02-26 17:01
 */
@Controller
@Api(value = "工作流用户与组控制器", description = "工作流定义")
@RequestMapping(value="/pcwindow")
public class ActIdentityAction extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ActIdentityAction.class);

    //创建标识：0
    private static final String CREATE_TYPE = "0";

    private static final String TING_LEADER = "厅领导";

    private static final String BUMEN_LEADER = "部门领导";

    private static final String PUTONG_LEADER = "普通用户";

    @Autowired
    IdentityService identityService;

    @Autowired
    private ActivitiService activitiService;

    @Autowired
    private UserService userService;

    @Autowired
    private UpmsUserRoleService upmsUserRoleService;

    /**
     * @author:zyp
     * @description 跳转到用户与组的页面
     * @date: 2019/2/26 17:15
     * @return
     */
    @ApiOperation(value = "跳转到用户与组的页面")
    @RequiresPermissions("upms:identity:read")
    @RequestMapping(value = "/toActIdentity")
    public String toActIdentity() {
        return "/activitiManager/actIdentity" ;
    }

    /**
     * @author:zyp
     * @description 查找组列表
     * @date: 2019/2/26 17:27
     * @return 
     */
    @ApiOperation(value = "查找组列表")
    @RequiresPermissions("upms:identity:read")
    @RequestMapping(value = "/getGroup")
    @ResponseBody
    public Object groupList(@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                            @RequestParam(required = false, defaultValue = "", value = "search") String search,
                            @RequestParam(required = false, defaultValue = "", value = "userId") String userId
    ) {
        GroupQuery groupQuery = identityService.createGroupQuery();
        if (StringUtils.isNotBlank(userId)){
            groupQuery.groupMember(userId);
        }
        List<Group> rows = groupQuery.list();
        Map<String, Object> result = new HashMap<>(2);
        List<Group>  finalList = activitiService.pagingActGroup(rows,offset,limit,search);
        result.put("rows",finalList);
        result.put("total",rows.size());
        return result;
    }

    /**
     * @author:zyp
     * @description 根据groupId获取group
     * @date: 2019/2/27 10:15
     * @return 
     */
    @ApiOperation(value = "根据groupId获取group")
    @RequiresPermissions("upms:identity:read")
    @RequestMapping(value = "/getGroupByGroupId", method = RequestMethod.POST)
    @ResponseBody
    public Group getGroupByGroupId(String id){
        Group group = identityService.createGroupQuery().groupId(id).singleResult();
        return group;
    }

    /**
     * @author:zyp
     * @description 保存Group
     * @date: 2019/2/27 9:38
     * @return 
     */
    @ApiOperation(value = "保存组")
    @RequiresPermissions("upms:identity:create")
    @RequestMapping(value = "/saveGroup", method = RequestMethod.POST)
    @ResponseBody
    public Object saveGroup(@RequestParam("groupId") String groupId,
                            @RequestParam("groupName") String groupName,
                            @RequestParam("type") String type,
                            @RequestParam("operateType") String operateType) {
        Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
        if (group == null) {
            group = identityService.newGroup(groupId);
        }else if(CREATE_TYPE.equals(operateType)){
            return 0;
        }
        group.setName(groupName);
        group.setType(type);
        identityService.saveGroup(group);
        return 1;
    }

    /**
     * @author:zyp
     * @description 删除组
     * @date: 2019/2/27 9:42
     * @return
     */
    @ApiOperation(value = "删除组")
    @RequiresPermissions("upms:identity:delete")
    @RequestMapping(value = "/deleteGroup", method = RequestMethod.POST)
    @ResponseBody
    public Object deleteGroup(String ids) {
        if (!StringUtils.isBlank(ids)) {
            String[] idArray = ids.split("-");
            for (String id : idArray) {
                if (StringUtils.isBlank(id)) {
                    continue;
                }
                identityService.deleteGroup(id);
            }
        }
        return 1;
    }

    /**
     * @author:zyp
     * @description 查找所有用户，不分页
     * @date: 2019/2/27 11:06
     * @return
     */
    @ApiOperation(value = "查找组内的所有用户，不分页")
//    @RequiresPermissions("upms:identity:read")
    @RequestMapping(value = "/showNoHaveUser/{id}")
    @ResponseBody
    public Object showNoHaveUser(@PathVariable("id") String id) {
        Map<String, Object> result = new HashMap<>(2);
        UserQuery userQuery = identityService.createUserQuery().orderByUserId().desc();
        List<User> allList = userQuery.list();
        userQuery.memberOfGroup(id);
        List<User> idList = userQuery.list();
        List<User> userSet = new ArrayList<>();
        for (User allUser : allList){
            //判断循环是否存在两者是否含有相同的内容，默认没有
            boolean flag = false;
            for (User idUser : idList){
                //如果存在相同的，则将循环退出
                if(idUser.getId().equals(allUser.getId())){
                    flag = true;
                    break;
                }
            }
            if(!flag){
                userSet.add(allUser);
            }
        }
        result.put("rows",userSet);
        result.put("total",userSet.size());
        return result;
    }

    /**
     * @author:zyp
     * @description 根据组id，查找组中的用户
     * @date: 2019/2/27 9:48
     * @return 
     */
    @ApiOperation(value = "根据组id，查找组中的用户")
//    @RequiresPermissions("upms:identity:read")
    @RequestMapping(value = "/showHaveUser/{id}")
    @ResponseBody
    public Object showHaveUser(@PathVariable("id") String id) {
        Map<String, Object> result = new HashMap<>(2);
        UserQuery userQuery = identityService.createUserQuery().orderByUserId().desc();
        userQuery.memberOfGroup(id);
        List<User> list = userQuery.list();
        result.put("rows",list);
        result.put("total",list.size());
        return result;
    }

    /**
     * @author:zyp
     * @description 查找所有用户，不分页
     * @date: 2019/2/27 11:06
     * @return
     */
    @ApiOperation(value = "查找所有用户，不分页")
//    @RequiresPermissions("upms:identity:read")
    @RequestMapping(value = "/showAllUser")
    @ResponseBody
    public Object showAllUser() {
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        List<UpmsUser> users = userService.findByName(username);
        UpmsUser user = new UpmsUser();
        if(users!=null&&users.size()>0){
            user = users.get(0);
        }
        Integer userId = user.getUserId();
        //根据用户ID，获取该用户的所有角色
        List<UpmsRole> roles = upmsUserRoleService.selectRolesByUserId(userId);
        //角色名称组
        List<String> roleNames = new ArrayList<>();
        Map<String,Integer> tempMap = new HashMap<>();
        for(UpmsRole upmsRole:roles){
            roleNames.add(upmsRole.getName());
            tempMap.put(upmsRole.getName(),upmsRole.getRoleId());
        }
        Map<String, Object> result = new HashMap<>(2);
        UserQuery userQuery = identityService.createUserQuery().orderByUserId().desc();
        List<User> allList = userQuery.list();
        List<User> finalList = new ArrayList<>();
        List<Integer> usersIds = null;
        //如果用户为厅领导 //只能选择厅领导
        if(roleNames.contains(TING_LEADER)){
            Integer roleId = tempMap.get(TING_LEADER);
            //根据角色ID，获取该角色的所有用户id
            usersIds = upmsUserRoleService.selectRolesByRoleId(roleId);
            for (User user1 : allList){
                if(usersIds.contains(user1.getId())){
                    finalList.add(user1);
                }
            }
            //如果该用户为部门领导，获取上级厅领导
        }else if(roleNames.contains(BUMEN_LEADER)){
            //根据厅领导角色ID，获取该角色的所有用户id
            usersIds = upmsUserRoleService.selectRolesByTingLeader();
            for (User user1 : allList){
                int nowUserId = MathUtils.object2Int(user1.getId());
                if(usersIds.contains(nowUserId)){
                    finalList.add(user1);
                }
            }
            //如果该用户为普通用户，获取上级部门领导
        }else if(roleNames.contains(PUTONG_LEADER)){
            //获取其部门的部门领导
            usersIds = upmsUserRoleService.selectRolesByBuMenLeader(userId);
            for (User user1 : allList){
                int nowUserId = MathUtils.object2Int(user1.getId());
                if(usersIds.contains(nowUserId)){
                    finalList.add(user1);
                }
            }
        }else{
            usersIds = new ArrayList<>();
            //获取其部门的部门领导
            List<Integer>  firstUsersIds = upmsUserRoleService.selectRolesByBuMenLeader(userId);
            //根据厅领导角色ID，获取该角色的所有用户id
            List<Integer>  secondUsersIds = upmsUserRoleService.selectRolesByTingLeader();
            if(firstUsersIds!=null){
                usersIds.addAll(firstUsersIds);
            }
            usersIds.addAll(secondUsersIds);
            for (User user1 : allList){
                int nowUserId = MathUtils.object2Int(user1.getId());
                if(usersIds.contains(nowUserId)){
                    finalList.add(user1);
                }
            }
        }
        result.put("rows",finalList);
        result.put("total",finalList.size());
        return result;
    }

    /**
     * @author:zyp
     * @description 为组设置所属用户
     * @date: 2019/2/27 9:50
     * @return 
     */
    @ApiOperation(value = "为用户设置所属组")
    @RequiresPermissions("upms:identity:groupSetUser")
    @RequestMapping(value = "/groupSetUser")
    @ResponseBody
    public Object groupSetUser(@RequestParam("groupId") String groupId, @RequestParam("userIds") String userIds) {
        List<User> userInDb = identityService.createUserQuery().memberOfGroup(groupId).list();
        for (User user : userInDb) {
            identityService.deleteMembership(user.getId(), groupId);
        }
        if (StringUtils.isNotBlank(userIds)){
            String[] users = userIds.split("-");
            for (String userId : users) {
                identityService.createMembership(userId, groupId);
            }
        }
        return  1;
    }

}